﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace mirror
{
    class SpriteManager : Singleton<SpriteManager>
    {
        private ContentManager mContentManager;
        private SpriteBatch mSpriteBatch;
        private Dictionary<string, Texture2D> mTextureCache;

        public SpriteManager()
        {
        }
        
        public void Initialise(ContentManager content, SpriteBatch batch)
        {
            mContentManager = content;
            mSpriteBatch = batch;

            mTextureCache = new Dictionary<string, Texture2D>(64);
        }

        public Sprite FindSprite(string spriteName)
        {
            Sprite sprite = new Sprite();
            if (mTextureCache.ContainsKey(spriteName))
            {
                Texture2D texture;
                mTextureCache.TryGetValue(spriteName, out texture);
                sprite.setTexture(texture);
            }
            else
            {
                Texture2D texture = CreateTexture(spriteName);
                sprite.setTexture(texture);
            }
            return sprite;
        }

        public Texture2D GetTexture(string spriteName)
        {
            if(mTextureCache.ContainsKey(spriteName))
            {
                Texture2D texture; 
                mTextureCache.TryGetValue(spriteName, out texture);
                return texture;
            }
            else
                return CreateTexture(spriteName);
        }

        public Texture2D CreateTexture(string spriteName)
        {
            Texture2D texture = mContentManager.Load<Texture2D>(spriteName);
            mTextureCache.Add(spriteName, texture);
            return texture;
        }

        public void DrawMe(Sprite zSprite)
        {
            mSpriteBatch.Begin();
            mSpriteBatch.Draw(zSprite.getTexture(), 
                       zSprite.GetPos(), 
                       zSprite.GetRectangle(), 
                       Color.White, 
                       zSprite.GetOrientation(), 
                       zSprite.GetTextureDimensions(),
                       zSprite.getScale(), 
                       SpriteEffects.None, 
                       zSprite.getDepth());
            mSpriteBatch.End();
        }

        public SpriteBatch GetSpriteBatch()
        {
            return mSpriteBatch;
        }
    }
}
